<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Autorization extends Controller {

	//protected $_data;
	public function before()
	{
		parent::before();
		
		$this->_data['controller'] = $this->request->controller();
		$this->_data['action'] = $this->request->action();
		$this->_data['orderid'] = $this->request->param('orderid',NULL);
		$this->_data['itemid'] = $this->request->param('itemid',NULL);
		
	    $this->a2 = A2::instance('a2');
		$this->a1 = $this->a2->a1;
		$this->_data['user'] = $this->user = $this->a2->get_user();
		//print_r($this->_data['user']);
		if ($this->request->action() != 'login' AND $this->request->action() != 'registration' AND $this->request->action() != 'remind' AND !$this->user)
		{			//echo 'not logged in';
			$this->redirect('login');		}
		elseif($this->user) 
		{
			$roles = $this->user->roles->where('name','!=','login')->find_all();
			foreach($roles as $role)
			{
				$this->_data['role']['id'] = $role->id;
				$this->_data['role']['name'] = $role->name;
			}
			//echo $data->get('name');
			
			//Auth::instance()->get_user()->roles->find_all()
		}
	}

	public function after()
	{
		//Debug::vars($this->_data['interfaces']);
		//print_r($this->_data['interfaces']);
		parent::after();
	}


	public function action_login()
	{
		if($this->user) //cannot create new accounts when a user is logged in
		{
			$this->redirect('/');
			//$this->redirect(!empty($this->user->last_uri)?$this->user->last_uri:$this->_data['type']);
		}
        elseif (!empty($_POST))
        {
			$post = Validation::factory($this->request->post())
				->rule('username', 'not_empty')
				->rule('username', 'min_length', array(':value', 3))
				->rule('username', 'max_length', array(':value', 32))
				->rule('username', 'regex', array(':value', '/^[0-9a-z_.-]+$/iD'))
				->rule('password', 'not_empty')
				->rule('password', 'min_length', array(':value', 4))
				->rule('password', 'max_length', array(':value', 32))
				->rule('username', 'regex', array(':value', '/^[@#%\^,&\*\?\{\}\(\)\'\"~`0-9a-z_\.-]+$/iD'));
            //echo 'check'.$this->a1->login($post['username'],$post['password'],FALSE);
			if(!$post->check())
			{
				$this->_data['errors'][] = Kohana::message('login', 'validate');
			}
			elseif($this->a1->login($post['username'],$post['password'],FALSE))
			{
				//$this->_data['user'] = $this->user = $this->a2->get_user();
				$this->redirect('/');
			}
			else 
			{
				$this->_data['errors'][] = Kohana::message('login', 'errors');
			}
        }

        $this->response->body(View::factory($this->_data['controller'].'/'.$this->_data['action'],$this->_data));
	}

	public function action_logout()
	{
		/*
		$this->user = $this->a2->get_user();
		$time=time();
		$query = DB::insert('user_logs',array('user_id', 'time', 'action'))
			->values(array($this->user->id, $time, 'вышел'))
			->execute();
		*/
		$this->a1->logout();
		$this->_data['user'] = $this->user = NULL;
		$this->redirect('login');
	}
	
	public function action_registration()
	{
		if($this->user) //cannot create new accounts when a user is logged in
		{
			$this->redirect('/');
		}
		if (!empty($_POST))
		{
			try
			{
				$user = ORM::factory('User');
				$user->username = $_POST['username'];
				$user->password = $_POST['password'];
				$user->email = $_POST['email'];
				$post = Validation::factory($this->request->post())
					->rule('password_confirm', 'matches', array(':validation', ':field', 'password'));
			
				if(!$post->check())
				{
					$this->_data['errors'][] = Kohana::message('login', 'validate');
				}
				else 
				{
					// Pass the extra rules to be validated with the model
					$user->save($post);
					$user->add('roles', ORM::factory('Role', array('name' => 'login')));
					$user->add('roles', ORM::factory('Role', array('id' => $_POST['role'])));
					$message = array(
							'subject' => 'Регистрация на сайте',
							'body'    => View::factory('email/'.$this->_data['action'],array('password'=>$_POST['password'],'username'=>$user->username))->render(),
							'from'    => array('noreply@lidocs.ru' => 'LIDOCS.RU'),
							'to'      => array($user->email=>$user->username)
					);
					Model::factory('Book')->into_stack(serialize($message));
				}
			}
			catch (ORM_Validation_Exception $e)
			{
				print_r($e->errors('models'));
			}
			//$this->redirect('login');
		}
		$this->response->body(View::factory($this->_data['controller'].'/'.$this->_data['action'],$this->_data));

	}

	public function action_remind()
	{
		if($this->user) //cannot remind new accounts when a user is logged in
		{
			$this->redirect('/');
		}		
		elseif (!empty($_POST) AND $this->request->param('remind',FALSE)===FALSE)
		{
			try
			{
				$user = ORM::factory('User')
					->where('username', '=', $_POST['username'])
					->find();
				if (!empty($user->email))
				{
					$code = substr(md5(microtime(TRUE)),0,8);
					$user->remind = $code;
					$user->save();
					$message = array(
						'subject' => 'Сброс пароля',
						'body'    => View::factory('email/'.$this->_data['action'],array('code'=>$code))->render(),
						'from'    => array('noreply@lidocs.ru' => 'LIDOCS.RU'),
						'to'      => array($user->email=>$user->username)
					);
					Model::factory('Book')->into_stack(serialize($message));
					$this->response->body(View::factory($this->_data['controller'].'/'.$this->_data['action'].'sent'));
				}
				
			}
			catch (ORM_Validation_Exception $e)
			{
				$errors = $e->errors('models');
			}
	
		}
		elseif ($this->request->param('remind',FALSE)!==FALSE)
		{
			$user = ORM::factory('User')
				->where('remind', '=', $this->request->param('remind'))
				->find();
			if (!empty($user->remind))
			{
				$password = Text::random('alpha',6);
				$user->remind = '';
				$user->password = $password;
				$user->save();
				$message = array(
					'subject' => 'Ваш новый пароль',
					'body'    => View::factory('email/'.$this->_data['action'].'sent',array('password'=>$password,'username'=>$user->username))->render(),
					'from'    => array('noreply@lidocs.ru' => 'LIDOCS.RU'),
					'to'      => array($user->email=>$user->username)
				);
				Model::factory('Book')->into_stack(serialize($message));
				$this->response->body(View::factory($this->_data['controller'].'/'.$this->_data['action'].'sent'));
				//if(Email::send('default', $message['subject'], $message['body'], $message['from'], $message['to'], 'text/html')==TRUE)
				//{
					
				//}
			}
			else 
			{
				throw new HTTP_Exception_404('Запрашиваемая страница несуществует!');
			}
		}
		else
		{
			$this->response->body(View::factory($this->_data['controller'].'/'.$this->_data['action']));
		}
	}	
/*	
	public function get_role_id()
	{        $roles = array();
        // We need to explicitly call find_all() to get the roles. Lazy loading...

        $my_roles = $this->roles->find_all();
        foreach ($my_roles as $role)
        {
            // Now grab the names of the roles. Used on the ACL module
            $roles[] = $role->name;
        }

        return $roles;	}
*/
} // End Autorization